import { createRouter, createWebHashHistory } from 'vue-router';
import { foldMenuStore } from '@/store/foldMenu';
import { tagsViewStore } from '@/store/tagsView';
import { whiteList } from '@/config';
import { isLogin } from '@/utils';
import LayoutComponent from '@/layout/Index.vue';
import { menusAPI } from '@/api/menus';
// import fourHundredOne from '@/views/exception/401.vue';
// import fourHundredThree from '@/views/exception/403.vue';
// import fourHundredFour from '@/views/exception/404.vue';
// import fiveHundred from '@/views/exception/500.vue';
// import fiveHundredThree from '@/views/exception/503.vue';
//常规配置
const constantRoutes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/pages/login/Index.vue'),
  },
  {
    path: '/redirect',
    component: LayoutComponent,
    meta: { title: '刷新', hidden: true, noShowTabbar: true },
    children: [
      {
        path: '/redirect/:path(.*)*',
        component: () => import('@/views/redirect/Index.vue'),
        meta: {
          title: 'refresh',
        },
      },
    ],
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes,
});
const LAYOUT = 'Layout',
  HOME = 'Home';
const generateRoutes = (routes) => {
  return routes.map((r) => {
    if (r.component === LAYOUT) {
      r.component = LayoutComponent;
    } else if (r.component === HOME) {
      // r.component = HomeComponent;
    } else {
      const filePath = r.component;
      r.component = () =>
        new Promise((resolve, reject) => {
          import(`../views/${filePath}.vue`)
            .then((module) => {
              // 中间层加组件名
              module.default.name = r.name;
              resolve(module);
            })
            .catch(reject);
        });
    }
    if (r.children && r.children.length > 0) {
      r.children = generateRoutes(r.children);
    }
    return r;
  });
};
const loadMenus = async (to, next) => {
  const foldMenu = foldMenuStore();
  const res = await menusAPI();

  if (res.code == 200) {
    foldMenu.setMenus(res.data);
    const routes = generateRoutes(res.data);
    // 4. 加入到路由对象中
    routes.forEach((route) => {
      router.addRoute(route);
    });
    // 4.5 最后加入404
    // router.addRoute({
    //   path: '*',
    //   component: NotFoundComponent,
    //   // redirect:{ name:'404' } 已经现有的路由中
    // });
    // 这次无效的导航 要重新来过
    next({ ...to, replace: true /*不额外向历史记录添加一条访问记录*/ });
  } else {
    console.log('菜单获取失败');
  }
};
router.beforeEach((to, from, next) => {
  const foldMenu = foldMenuStore();
  const tagsView = tagsViewStore();
  if (whiteList.includes(to.path)) {
    return next();
  }
  if (!isLogin()) {
    // to.path: /dasdsadsadsad/dsadasdsa?id=1
    return next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
  }
  // 登录后, 是否已经有动态菜单
  if (foldMenu.menus.length === 0) {
    return loadMenus(to, next);
  }
  // 但是在登录之前已经加载过路由
  // 已经有路由菜单,放行到login
  foldMenu.changeDefaultActive(to.path);
  // const dashboard = router
  //   .getRoutes()
  //   .find((item) => item.path == '/dashboard' && Object.keys(item.meta).length);
  // if (tagsView.visitedViews.length == 0) {
  //   tagsView.addView(dashboard);
  // }
  if (to.meta.isreveal) return next();
  foldMenu.addCache({
    name: to.name, // 组件名称
    title: to.meta.title,
  });
  next();
});

export default router;
